package com.back.controller;

import com.back.common.utils.Result;
import com.back.dto.JobDTO;
import com.back.service.IJobService;
import com.back.vo.JobListVO;
import com.back.vo.JobVO;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  职位前端控制器
 * </p>
 *
 * @author liyang
 * @since 2025-04-26
 */
@RestController
@RequestMapping("/api")
public class JobController {

    @Autowired
    private IJobService jobService;

    /**
     * 获取职位列表
     */
    @GetMapping("/jobs")
    public Result getJobs(
            @RequestParam(value = "page", defaultValue = "1") Integer page,
            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) String location,
            @RequestParam(required = false) String category,
            @RequestParam(required = false) String salary,
            @RequestParam(required = false) String experience,
            @RequestParam(required = false) String education,
            @RequestParam(required = false) String tags,
            @RequestParam(required = false) Long companyId,
            @RequestParam(required = false) String status) {
        
        // 构建查询参数
        Map<String, Object> params = new HashMap<>();
        if (keyword != null) params.put("keyword", keyword);
        if (location != null) params.put("location", location);
        if (category != null) params.put("category", category);
        if (salary != null) params.put("salary", salary);
        if (experience != null) params.put("experience", experience);
        if (education != null) params.put("education", education);
        if (tags != null) params.put("tags", tags);
        if (companyId != null) params.put("companyId", companyId);
        if (status != null) params.put("status", status);
        
        // 查询职位列表
        IPage<JobListVO> jobPage = jobService.getJobList(page, pageSize, params);
        
        // 返回结果
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("total", jobPage.getTotal());
        resultMap.put("list", jobPage.getRecords());
        resultMap.put("page", jobPage.getCurrent());
        resultMap.put("pageSize", jobPage.getSize());
        
        return Result.ok().data(resultMap);
    }
    
    /**
     * 获取职位详情
     */
    @GetMapping("/jobs/{id}")
    public Result getJobDetail(@PathVariable Long id, HttpServletRequest request) {
        // 增加浏览次数
        jobService.incrementJobViews(id);
        
        // 获取职位详情
        JobVO jobVO = jobService.getJobDetail(id);
        
        if (jobVO != null) {
            return Result.ok().data("data", jobVO);
        } else {
            return Result.error().message("职位不存在或已被删除");
        }
    }
    
    /**
     * 创建职位
     */
    @PostMapping("/jobs")
    @PreAuthorize("hasAuthority('company')")
    public Result createJob(@RequestBody JobDTO jobDTO, HttpServletRequest request) {
        // 从JWT中获取当前用户信息
        // 此处简化，实际应从token中获取
        Long companyId = 1L; // 示例，实际应从token中获取
        Long recruiterId = 1L; // 示例，实际应从token中获取
        
        try {
            JobVO jobVO = jobService.createJob(jobDTO, companyId, recruiterId);
            return Result.ok().message("创建成功").data("data", jobVO);
        } catch (Exception e) {
            return Result.error().message("创建失败：" + e.getMessage());
        }
    }
    
    /**
     * 更新职位
     */
    @PutMapping("/jobs/{id}")
    @PreAuthorize("hasAuthority('company')")
    public Result updateJob(@PathVariable Long id, @RequestBody JobDTO jobDTO, HttpServletRequest request) {
        // 从JWT中获取当前用户信息
        Long companyId = 1L; // 示例，实际应从token中获取
        
        boolean result = jobService.updateJob(id, jobDTO, companyId);
        if (result) {
            JobVO jobVO = jobService.getJobDetail(id);
            return Result.ok().message("更新成功").data("data", jobVO);
        } else {
            return Result.error().message("更新失败：职位不存在或无权限修改");
        }
    }
    
    /**
     * 删除职位
     */
    @DeleteMapping("/jobs/{id}")
    @PreAuthorize("hasAuthority('company')")
    public Result deleteJob(@PathVariable Long id, HttpServletRequest request) {
        // 从JWT中获取当前用户信息
        Long companyId = 1L; // 示例，实际应从token中获取
        
        boolean result = jobService.deleteJob(id, companyId);
        if (result) {
            return Result.ok().message("删除成功");
        } else {
            return Result.error().message("删除失败：职位不存在或无权限删除");
        }
    }
    
    /**
     * 关闭职位招聘
     */
    @PutMapping("/jobs/{id}/close")
    @PreAuthorize("hasAuthority('company')")
    public Result closeJob(@PathVariable Long id, HttpServletRequest request) {
        // 从JWT中获取当前用户信息
        Long companyId = 1L; // 示例，实际应从token中获取
        
        boolean result = jobService.closeJob(id, companyId);
        if (result) {
            Map<String, Object> data = new HashMap<>();
            data.put("id", id);
            data.put("status", "closed");
            data.put("updateTime", System.currentTimeMillis());
            
            return Result.ok().message("职位已关闭").data(data);
        } else {
            return Result.error().message("操作失败：职位不存在或无权限操作");
        }
    }
    
    /**
     * 重新开启职位招聘
     */
    @PutMapping("/jobs/{id}/reopen")
    @PreAuthorize("hasAuthority('company')")
    public Result reopenJob(@PathVariable Long id, HttpServletRequest request) {
        // 从JWT中获取当前用户信息
        Long companyId = 1L; // 示例，实际应从token中获取
        
        boolean result = jobService.reopenJob(id, companyId);
        if (result) {
            Map<String, Object> data = new HashMap<>();
            data.put("id", id);
            data.put("status", "active");
            data.put("updateTime", System.currentTimeMillis());
            
            return Result.ok().message("职位已重新开启").data(data);
        } else {
            return Result.error().message("操作失败：职位不存在或无权限操作");
        }
    }
    
    /**
     * 获取职位申请状态
     */
    @GetMapping("/jobs/{id}/application-status")
    @PreAuthorize("hasAuthority('job_seeker')")
    public Result getApplicationStatus(@PathVariable Long id, HttpServletRequest request) {
        // 从JWT中获取当前用户信息
        Long userId = 2L; // 示例，实际应从token中获取
        
        Map<String, Object> status = jobService.getApplicationStatus(id, userId);
        return Result.ok().data("data", status);
    }
    
    /**
     * 获取相似职位推荐
     */
    @GetMapping("/jobs/{id}/similar")
    public Result getSimilarJobs(
            @PathVariable Long id,
            @RequestParam(value = "limit", defaultValue = "5") Integer limit) {
        
        List<JobListVO> similarJobs = jobService.getSimilarJobs(id, limit);
        return Result.ok().data("data", similarJobs);
    }
    
    /**
     * 标记职位不感兴趣
     */
    @PostMapping("/jobs/{id}/not-interested")
    @PreAuthorize("hasAuthority('job_seeker')")
    public Result markJobNotInterested(@PathVariable Long id, HttpServletRequest request) {
        // 从JWT中获取当前用户信息
        Long userId = 2L; // 示例，实际应从token中获取
        
        boolean result = jobService.markJobNotInterested(id, userId);
        if (result) {
            return Result.ok().message("操作成功");
        } else {
            return Result.error().message("操作失败");
        }
    }
}
